package com.qqtech.qquan.user.controller;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.BizzLevel2Enum;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.pub.enums.PubCommentStatusDictEnum;
import com.qqtech.qquan.pub.model.PubCommentVo;
import com.qqtech.qquan.pub.model.PubPraise;
import com.qqtech.qquan.pub.model.PubPraiseQuery;
import com.qqtech.qquan.pub.model.PubPraiseVo;
import com.qqtech.qquan.pub.service.PubCommentService;
import com.qqtech.qquan.pub.service.PubConcernService;
import com.qqtech.qquan.pub.service.PubPraiseService;
import com.qqtech.qquan.push.service.PushBizzService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.user.enums.UserTopicStatusDictEnum;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserTopic;
import com.qqtech.qquan.user.model.UserTopicQuery;
import com.qqtech.qquan.user.model.UserTopicVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserFriendService;
import com.qqtech.qquan.user.service.UserTopicService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/user/topic")
public class UserTopicController extends BaseWebController<UserTopic, UserTopicQuery> {
	@Resource
	private UserTopicService userTopicService;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private PubCommentService pubCommentService;

	@Resource
	private PubPraiseService pubPraiseService;

	@Resource
	private PubConcernService pubConcernService;

	@Resource
	private UserFriendService userFriendService;
	@Resource
	private PushBizzService pushBizzService;

	@Override
	protected BaseService<UserTopic> getBaseService() {
		return userTopicService;
	}

	/**
	 * 友事详情
	 * 
	 * @param userTopicQuery
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody UserTopicQuery userTopicQuery) {
		Result result = new Result();
		userTopicQuery.setStatus(UserTopicStatusDictEnum.NORMAL.getCode());
		userTopicQuery.setIsShow(YesNoEnum.YES.getCode());
		UserTopicVo userTopicVo=userTopicService.getById(userTopicQuery.getId());
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		userVo = userBaseService.getById(userTopicVo.getCreatorId());
		userTopicVo.setCreatorImg(userVo.getLogo());
		userTopicVo.setCreatorName(userVo.getNick());
		setPraiseBoolean4Topic(userTopicVo);//处理是否已点赞
		addPraiseUserList(userTopicVo);
		addCommentList(userTopicVo);
		userTopicVo.setIndex(0);
		userTopicVo.setImgString(userTopicVo.getImg(),SysConst.IMG_POSTFIX);//友事图片
		if (!super.isVisitor()) {
			Integer curUserId = super.getUserId();
			if(curUserId.intValue() == userTopicVo.getCreatorId()){
				userTopicVo.setBelongToMe(true);
			}
		}
		result.put("datailVo", userTopicVo);
		return result;
	}
	/**
	 * 用户友事
	 * 
	 * @param topicQuery
	 * @return
	 */
	@RequestMapping(value = "/page")
	@ResponseBody
	public Result page(@RequestBody UserTopicQuery userTopicQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		userTopicQuery.setStatus(UserTopicStatusDictEnum.NORMAL.getCode());
		userTopicQuery.setIsShow(YesNoEnum.YES.getCode());
		
		if (!super.isVisitor()) {
			// 我的好友id列表（包括我自己）
			List<Integer> myFriendIds = userFriendService.queryMyFriendIds(curUserId);
			if(myFriendIds!=null && myFriendIds.size()>0){
				userTopicQuery.setUserIds(myFriendIds);
			}else{
				myFriendIds=new ArrayList<Integer>();
				myFriendIds.add(curUserId);
				userTopicQuery.setUserIds(myFriendIds);
			}
			Pageable pageKit = new PageKit(userTopicQuery.getPage(), new PageOrder(Direction.DESC, "id"));
			Page<UserTopicVo> topicPage = userTopicService.queryPageList(userTopicQuery, pageKit);
			List<UserTopicVo> topicList = topicPage.getContent();
			if (topicList != null && topicList.size() > 0) {
				LinkedHashMap<Integer, UserBaseVo> myFriendMap = userBaseService.queryUserMapListByUserIds(myFriendIds);
				List<Integer> myPraiseTopicIds = getUserPraisedTopicIds(super.getUserId());
				
				for (UserTopicVo topicVo : topicList) {
					userVo = myFriendMap.get(topicVo.getCreatorId());
					if(userVo!=null){
						topicVo.setCreatorImg(userVo.getLogo());
						topicVo.setCreatorName(userVo.getNick());
					}
					if(!myPraiseTopicIds.isEmpty()){
						if(myPraiseTopicIds.contains(topicVo.getId())){
							topicVo.setIsPraised(YesNoEnum.YES.getCode());//处理是否已点赞
						}
					}
					addPraiseUserList(topicVo);
					addCommentList(topicVo);
					topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);//友事图片
					if (null != curUserId) {
						if(curUserId.intValue() == topicVo.getCreatorId()){
							topicVo.setBelongToMe(true);
						}
					}
				}
			}
			result.put("topicPage", topicPage);
		} else {
			result.put("topicPage", null);
		}
		return result;
	}

	// 为话题-附加 评论数量、点赞
	private void setPraiseBoolean4Topic(UserTopicVo topicVo) {
		topicVo.setIsPraised(YesNoEnum.NO.getCode());
		if(!super.isVisitor()){
			if(pubPraiseService.isPraisedByUser(topicVo.getId(), BizzLevel2Enum.USER_TOPIC.getCode(), super.getUserId())){
				topicVo.setIsPraised(YesNoEnum.YES.getCode());
			}
		}
	}

	// 为话题-附加点赞人列表
	private void addPraiseUserList(UserTopicVo topicVo) {
		List<PubPraise> praiseList = pubPraiseService.queryPraiseListByBizz(topicVo.getId(),BizzLevel2Enum.USER_TOPIC.getCode());
		String praiseUserList = "";
		for (int i = 0; i < praiseList.size(); i++) {
			PubPraise praise = praiseList.get(i);
			UserBase user = userBaseService.getById(praise.getCreatorId());
			if (i == praiseList.size() - 1) {
				praiseUserList = praiseUserList + user.getNick();
			} else {
				praiseUserList = praiseUserList + user.getNick() + " , ";
			}
		}
		topicVo.setPraiseUserList(praiseUserList);
	}

	// 为话题-附加评论信息
	private void addCommentList(UserTopicVo topicVo) {
		List<PubCommentVo> commentList = pubCommentService.queryCommentListByBizz(topicVo.getId(), BizzLevel2Enum.USER_TOPIC.getCode());
		if (commentList != null && commentList.size() > 0) {
			for (PubCommentVo pubCommentVo : commentList) {
				UserBaseVo user = userBaseService.getById(pubCommentVo.getCreatorId());
				pubCommentVo.setCreatorImg(user.getLogo());
				pubCommentVo.setCreatorName(user.getNick());
				pubCommentVo.setBeCommented(false);
				pubCommentVo.setBeCommentedName("");
				if (pubCommentVo.getBeCommentedId() != null) {
					PubCommentVo beCommentVo = pubCommentService.getById(pubCommentVo.getBeCommentedId());
					if (beCommentVo != null) {
						UserBaseVo beCommentUser = userBaseService.getById(beCommentVo.getCreatorId());
						pubCommentVo.setBeCommentedName(beCommentUser.getNick());
						pubCommentVo.setBeCommented(true);
					}
				}
			}
		}
		topicVo.setCommentList(commentList);
	}

	/**
	 * 新增
	 * 
	 * @param userTopicVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create")
	@ResponseBody
	public Result create(@RequestBody UserTopicVo userTopicVo) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		userTopicVo.setCreatorId(curUserId);
		userTopicVo.setPv(0);
		userTopicVo.setStatus(UserTopicStatusDictEnum.NORMAL.getCode());
		userTopicVo.setIsShow(YesNoEnum.YES.getCode());
		userTopicService.addUserTopic(userTopicVo);
		pushBizzService.pubUserTopic(curUserId);
		return result;
	}

	/**
	 * 删除
	 * 
	 * @param userTopicVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Result delete(@RequestBody UserTopicVo userTopicVo) {
		Result result = new Result();
		UserTopicVo dleUserTopic = new UserTopicVo();
		dleUserTopic.setId(userTopicVo.getId());
		dleUserTopic.setIsShow(YesNoEnum.NO.getCode());
		dleUserTopic.setStatus(UserTopicStatusDictEnum.DELETE.getCode());
		userTopicService.updateById(dleUserTopic);
		return result;
	}
	
	/**
	 * 查询用户点赞过的友事ID列表
	 * @param userId
	 * @return
	 */
	private List<Integer> getUserPraisedTopicIds(Integer userId){
		List<Integer> topicIds = Lists.newArrayList();
		PubPraiseQuery praiseQ = new PubPraiseQuery();
		praiseQ.setBizzType(BizzLevel2Enum.USER_TOPIC.getCode());
		praiseQ.setCreatorId(userId);
		praiseQ.setStatus(PubCommentStatusDictEnum.NORMAL.getCode());
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "bizzId")); 
		List<PubPraiseVo> praiseList = pubPraiseService.queryList(praiseQ, pageKit);
		if(praiseList!=null && praiseList.size()>0){
			for(PubPraiseVo praise : praiseList){
				if(!topicIds.contains(praise.getBizzId())){
					topicIds.add(praise.getBizzId());
				}
			}
		}
		return topicIds;
	}
}
